//
//  CollectionCarVC.m
//  New_Runway
//
//  Created by mack on 2018/3/28.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "CollectionCarVC.h"
#import "NRWCarCarListCell.h"
#import "BuyCarDetailVC.h"
#import "NRWCarListsModel.h"

@interface CollectionCarVC ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate,LYSideslipCellDelegate>
@property(nonatomic, strong) UITableView *tableview;
@property (assign, nonatomic) NSInteger pageNo;
@property (nonatomic, strong) NSMutableArray *carArray;

@end

@implementation CollectionCarVC
-(NSMutableArray *)carArray{
    if (!_carArray) {
        _carArray = [[NSMutableArray alloc] init];
    }
    
    return _carArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationBarView.titleLabel.text = @"我的收藏";
    self.view.backgroundColor = kColorWhite();
    self.pageNo = 1;
    [self initTableview];
    [self loadCarList];
}
-(void)initTableview{
    kSelfWeak;
    self.tableview = [[UITableView alloc] init];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    _tableview.estimatedRowHeight = 0;
    _tableview.estimatedSectionHeaderHeight = 0;
    _tableview.estimatedSectionFooterHeight = 0;
    if (@available(iOS 11.0, *)) {
        self.tableview.contentInsetAdjustmentBehavior = UIApplicationBackgroundFetchIntervalNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = false;
    }
    self.tableview.backgroundColor = MAIN_COLOR();
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableview registerNib:[UINib nibWithNibName:@"NRWCarCarListCell" bundle:nil] forCellReuseIdentifier:@"NRWCarCarListCell"];
    self.tableview.mj_header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downPullRefresh)];
    self.tableview.mj_footer=[MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upPullLoadMore)];
    [self.view addSubview:self.tableview];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).mas_equalTo(self.navH);
        make.bottom.equalTo(weakSelf.view);
        make.left.right.equalTo(weakSelf.view);
    }];
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 110;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.carArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    Result *rt = self.carArray[indexPath.row];
    NRWCarCarListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NRWCarCarListCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.isBuyCar = YES;
    cell.delegate = self;
    cell.carModel = rt;
    if (rt.carSaleState == 30) {
        cell.backView.hidden = NO;
    }else{
        cell.backView.hidden = YES;

    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    Result *rt = self.carArray[indexPath.row];
    if (rt.carSaleState == 30) {
  
    }else{
        BuyCarDetailVC *detailVC = [[BuyCarDetailVC alloc] init];
        detailVC.carID = rt.carId;
        detailVC.carModel = rt;
        detailVC.isHistory = NO;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
  
    
}
-(void)downPullRefresh{
    self.pageNo = 1;
    [self loadCarList];
}
-(void)upPullLoadMore{
    self.pageNo += 1;
    [self loadCarList];
    
}
-(void)loadCarList{
    
    [SVProgressHUD show];
    NSDictionary *params = @{@"userId":[NRWCarUser sharedUser].userId,
                             @"pageIndex":@(self.pageNo),
                             @"pageSize":@(15)
                             };
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@",Api,collectionCarListApi] refreshRequest:YES cache:NO params:params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        if (self.pageNo == 1) {
            [self.carArray removeAllObjects];
        }
        
        NSArray *noticeArr = response[@"result"];
        for (NSDictionary *dic in noticeArr) {
            Result *rt = [Result mj_objectWithKeyValues:dic];
            [self.carArray addObject:rt];
        }
        if (self.carArray.count == 0) {
            [self.tableview addDefaultViewWithText:@"暂时没有数据哦！" defaultImageType:DefaultImageTypeNoData];
            
        }else{
            [self.tableview removeDefaultView];
        }
        
        [self.tableview reloadData];
        [self endRefresh];
        [SVProgressHUD dismiss];
    } failBlock:^(NSError *error) {
        [self endRefresh];
        [SVProgressHUD dismiss];
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
    }];
    
}
- (BOOL)sideslipCell:(LYSideslipCell *)sideslipCell canSideslipRowAtIndexPath:(NSIndexPath *)indexPath {
    Result *rt = self.carArray[indexPath.row];
    if (rt.carSaleState == 30) {
        return YES;
    }
    return NO;
    
}
- (NSArray<LYSideslipCellAction *> *)sideslipCell:(LYSideslipCell *)sideslipCell editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    kSelfWeak;
    LYSideslipCellAction *rowAction = [LYSideslipCellAction rowActionWithStyle:LYSideslipCellActionStyleNormal title:@"删除" handler:^(LYSideslipCellAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
        [weakSelf cancelCollection:indexPath];
      
        [sideslipCell hiddenSideslip];
        
    }];
    
    return @[rowAction];
    
    
}
-(void)cancelCollection:(NSIndexPath *)index{
    Result *rt = self.carArray[index.row];
    NSString *url = [NSString stringWithFormat:@"%@%@",Api,cancelCollectionCarApi];
    NSDictionary *params = @{
               @"carId":rt.carId,
               @"userId":[NRWCarUser sharedUser].userId
               };
    [YQNetworking postWithUrl:url refreshRequest:NO cache:NO params:params progressBlock:nil successBlock:^(id response) {
        if ([response[@"code"] isEqual:@1]) {
            [ShowMessage showHintMessage:@"删除成功" duration:2.0 withRemindId:remindSuccess];
            [self.carArray removeObject:rt];
            if (self.carArray.count == 0) {
                [self.view addDefaultViewWithText:@"暂无数据" defaultImageType:DefaultImageTypeNoData];
            }else{
                [self.view removeDefaultView];
            }
            [self.tableview reloadData];
        }
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
        
    }];
}


-(void)endRefresh{
    [self.tableview.mj_header endRefreshing];
    [self.tableview.mj_footer endRefreshing];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
